package com.scott.service.impl;

import com.github.pagehelper.PageInfo;
import com.scott.mapper.GeneratorMapper;
import com.scott.service.GeneratorService;
import com.scott.utils.GenUtils;
import com.scott.utils.PageHelperUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

@Service
public class GeneratorServiceImpl implements GeneratorService {
    @Autowired
    private GeneratorMapper generatorMapper;

    @Override
    public PageInfo<Map<String, Object>> query(Map<String, Object> map) {
        PageHelperUtil.startPage(map);
        return new PageInfo<>(generatorMapper.query(map));
    }


    @Override
    public Map<String, String> queryTable(Map<String, Object> queryMap) {
        return generatorMapper.queryTable(queryMap);
    }

    @Override
    public List<Map<String, String>> queryColumns(Map<String, Object> queryMap) {
        return generatorMapper.queryColumns(queryMap);
    }

    @Override
    public byte[] generatorCode(String tableName, String dbName) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        Map<String, Object> queryMap = new HashMap<>();

        queryMap.put("dbName", dbName);

        queryMap.put("tableName", tableName);
        //查询表信息
        Map<String, String> table = queryTable(queryMap);
        //查询列信息
        List<Map<String, String>> columns = queryColumns(queryMap);
        //生成代码
        GenUtils.generatorCode(table, columns, zip);
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    @Override
    public List<String> selectSchema() {
        return generatorMapper.selectSchema();
    }

}
